package com.authine.cloudpivot.engine;

import com.authine.cloudpivot.engine.component.PropertySourceListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * engine启动类.
 */
@SpringBootApplication
@EnableScheduling
public class EngineServiceApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(EngineServiceApplication.class);
        app.addInitializers(
                (ApplicationContextInitializer<ConfigurableApplicationContext>) EngineServiceApplication::checkApplicationConfig
        );
        app.addListeners(new PropertySourceListener());

        app.run(args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(EngineServiceApplication.class);
    }

    private static void checkApplicationConfig(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment env = applicationContext.getEnvironment();
        String driverClass = env.getProperty("spring.datasource.driver-class-name");

        if ("com.mysql.jdbc.Driver".equals(driverClass)) {
            String dataSourceUrl = env.getProperty("spring.datasource.url");
            if (dataSourceUrl == null || dataSourceUrl.trim().equals("")) {
                throw new ApplicationContextException("spring.datasource.url 未设置");
            }

            String url = dataSourceUrl.toLowerCase();
            if (!url.contains("characterencoding=utf-8") && !url.contains("characterencoding=utf8")) {
                String errMsg = "The driver type is mysql, please configure the character encoding.";
                System.err.println("\t\n*************************************************");
                System.err.println("\t\n" + errMsg);
                System.err.println("\t\n*************************************************");
                throw new ApplicationContextException("The driver type is mysql, please configure the character encoding.");
            }
        }
    }
}
